import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const authStore = useAuthStore()
    if (authStore.token) {
      config.headers['Token'] = `${authStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { data } = response
    // 这里根据你的后端接口结构进行调整
    if (data.message && (data.message.indexOf('登录已失效') > -1 || data.message.indexOf('未登录') > -1)) {
      const authStore = useAuthStore()
      authStore.logout()
      return ElMessage.error(data.message)
    }
    if (data.code && data.code !== 200) {
      ElMessage.error(data.message)
      return Promise.reject(new Error(data.message || 'Error'))
    }
    return data
  },
  error => {
    if (error.response && error.response.status === 401) {
      const authStore = useAuthStore()
      authStore.logout()
    }
    
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service